#!/usr/bin/perl

use DBI;
use Cwd;
use POSIX;
use strict;

# these hashes map column names in tables to their order
my %observation;
my %calibrators;
($observation{'source'},$observation{'ra'},$observation{'dec'},$observation{'n_if'},
 $observation{'if_freq'},$observation{'if_nchans'},$observation{'if_bw'},$observation{'time'},
 $observation{'arrayname'},$observation{'project_code'},$observation{'rpfits_file'},
 $observation{'cycle_time'},$observation{'offsource'},$observation{'onsource'},
 $observation{'scantype'},$observation{'calcode'},$observation{'stations'},
 $observation{'header_number'},$observation{'num_processed'},$observation{'processed_ids'},
 $observation{'id'},$observation{'az'},$observation{'el'},$observation{'attenmm'},
 $observation{'subrefl'},$observation{'corr_cfg'},$observation{'airtemp'},
 $observation{'chi'},$observation{'evector'},$observation{'jyperk'},
 $observation{'pntra'},$observation{'pntdec'},$observation{'relhumid'},
 $observation{'smonrms'},$observation{'wind'},$observation{'winddir'},
 $observation{'xtsys'},$observation{'ytsys'},$observation{'xyphase'},$observation{'xcaljy'},
 $observation{'ycaljy'},$observation{'xgtp'},$observation{'ygtp'},$observation{'xsdo'},
 $observation{'ysdo'},$observation{'pointcor'},$observation{'point_time'},
 $observation{'point_source'},$observation{'point_az'},$observation{'point_el'},
 $observation{'usable'})=
    (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,
     31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50);
($calibrators{'name'},$calibrators{'ra'},$calibrators{'dec'},$calibrators{'type'},
 $calibrators{'low_freq'},$calibrators{'high_freq'},$calibrators{'bandpass_21cm'},
 $calibrators{'bandpass_13cm'},$calibrators{'bandpass_6cm'},$calibrators{'bandpass_3cm'},
 $calibrators{'bandpass_12mm'},$calibrators{'bandpass_7mm'},$calibrators{'bandpass_3mm'})=
    (51,52,53,54,55,56,57,58,59,60,61,62,63);

# some default parameters
# the working directory
my $working_directory=".";

# my @highlow_21cm=(0,2000);
# my @highlow_13cm=(2000,4000);
# my @highlow_6cm=(4000,6500);
# my @highlow_3cm=(6500,10000);
# my @highlow_12mm=(15000,25000);
# my @highlow_7mm=(25000,55000);
# my @highlow_3mm=(80000,110000);

# database details
my $dsn="dbi:Pg:dbname=atca;host=mentok;port=5432";
my $user="postgres";
my $password="";

# Setup the database connection
my $dbh=DBI->connect($dsn,$user,$password,{ RaiseError => 0, AutoCommit => 1});

# go through the command-line arguments
my %options;
my @datasets;
$options{'precabb_data'}=0;
for (my $i=0;$i<=$#ARGV;$i++){
    if ($ARGV[$i] eq "--pre-cabb"){
	$options{'precabb_data'}=1;
    } elsif ($ARGV[$i] eq "--force-array"){
	# manual specification of the array
	$i++;
	$options{'force_array'}=$ARGV[$i];
    } elsif ($ARGV[$i] eq "--force-source"){
	# manual specification of the source name
	$i++;
	$options{'force_source'}=$ARGV[$i];
    } elsif ($ARGV[$i] eq "--is-flux"){
	# mark sources as flux calibrators
	$options{'is_flux'}=1;
    } else {
	# a Miriad dataset to import
	push @datasets,$ARGV[$i];
    }
}
# this script doesn't actually support CABB data yet, so quit unless we're
# dealing with pre-CABB data
if ($options{'precabb_data'}==0){
    die "This script does not yet support CABB data import\n";
}

# cycle through the datasets
for (my $i=0;$i<=$#datasets;$i++){
    # get as much data as we can
    print "\nworking on dataset ".$datasets[$i]."\n";
    my %parameters;
    $parameters{'working_directory'}=$working_directory;
    %parameters=&gather_data($datasets[$i],%parameters,%options);

    # now make some measurements
    %parameters=&make_measurements($datasets[$i],%parameters);

    # and put the data in the database
    $parameters{'calcode'}="C";
    $parameters{'project_code'}="C007";
    &db_insert_data($dbh,%parameters,%options);

#    if ($i>-1){
#	exit; # just for now anyway
#    }
}

$dbh->disconnect;

sub db_insert_data {
    my ($dbh,%parameters,%options)=@_;

    my $dat_query="INSERT INTO fluxdata (";
    my $sch_query="SELECT fluxdata.source,observation.time FROM ".
	"fluxdata,observation WHERE ".
	"observation.id=ANY(fluxdata.observation_ids) ";
    my $param_names;
    my $param_values;
    my $needs_and=1;
    $param_names="num_observations";
    $param_values="1";
    if ($parameters{'source'}){
	$param_names.=",source";
	$param_values.=",'".$parameters{'source'}."'";
	if ($needs_and==1){
	    $sch_query.="AND ";
	    $needs_and=0;
	}
	$sch_query.="fluxdata.source='".$parameters{'source'}."' ";
	$needs_and=1;
    }
    if ($parameters{'central_frequency'}){
	$param_names.=",frequency";
	$param_values.=",".$parameters{'central_frequency'};
	if ($needs_and==1){
	    $sch_query.="AND ";
	    $needs_and=0;
	}
	$sch_query.=" fluxdata.frequency::numeric=".$parameters{'central_frequency'}." ";
	$needs_and=1;
    }	
    if ($parameters{'nchannels'}){
	$param_names.=",nchans";
	$param_values.=",".$parameters{'nchannels'};
	if ($needs_and==1){
	    $sch_query.="AND ";
	    $needs_and=0;
	}
	$sch_query.=" fluxdata.nchans=".$parameters{'nchannels'}." ";
	$needs_and=1;
    }
    if ($parameters{'bandwidth'}){
	$param_names.=",bandwidth";
	$param_values.=",".$parameters{'bandwidth'};
    }
    $param_names.=",if_num";
    $param_values.=",0";
    $param_names.=",processed_as_flux,processed_as_bandpass,processed_as_phase";
    if ($options{'is_flux'}==1){
	$param_values.=",true,false,false";
    } else {
	$param_values.=",false,false,true";
    }
    if ($parameters{'central_frequency'}){
	$param_names.=",data_freq";
	$param_values.=",'{".($parameters{'central_frequency'}/1000.0)."}'";
    }
    if ($parameters{'bandwidth'}){
	$param_names.=",data_bw";
	$param_values.=",'{".($parameters{'bandwidth'}/1000.0)."}'";
    }
    if ($parameters{'tripleamp_value'}){
	$param_names.=",tripleamp_value";
	$param_values.=",'{".$parameters{'tripleamp_value'}."}'";
    }
    if ($parameters{'tripleamp_scatter_actual'}){
	$param_names.=",tripleamp_scatter_measured";
	$param_values.=",'{".$parameters{'tripleamp_scatter_actual'}."}'";
    }
    if ($parameters{'tripleamp_scatter_theoretical'}){
	$param_names.=",tripleamp_scatter_theoretical";
	$param_values.=",'{".$parameters{'tripleamp_scatter_theoretical'}."}'";
    }
    if ($parameters{'closure_phase_actual'}){
	$param_names.=",closurephase_measured";
	$param_values.=",'{".$parameters{'closure_phase_actual'}."}'";
    }
    if ($parameters{'closure_phase_theoretical'}){
	$param_names.=",closurephase_theoretical";
	$param_values.=",'{".$parameters{'closure_phase_theoretical'}."}'";
    }
    $param_names.=",quality_flag";
    $param_values.=",true";

    $dat_query.=$param_names.") VALUES(".$param_values.")";
    # check that this data point hasn't already been entered into the
    # database by checking that the time isn't the same
    print "query: $sch_query\n";
    my $sch=$dbh->prepare($sch_query);
    $sch->execute;
    my $time_already_entered=0;
    while (my @sch_response=$sch->fetchrow){
	my $timeentry=$sch_response[1];
	if ($timeentry eq $parameters{'time'}){
	    $time_already_entered=1;
	}
    }
    $sch->finish;
    # we only add the data if it hasn't already been entered
    if ($time_already_entered==1){
	print "won't enter this data, it already exists!\n";
    } else {
	print "entering data into database:\n";
	print "query: $dat_query\n";
	my $dat=$dbh->prepare($dat_query);
	my $rc=$dat->execute;
	if ($rc!=1){
	    # we may have gotten an error!
	    if ($dat->err!=0){
		print "error inserting into database!\n";
		$dat->finish;
		return -1;
	    }
	}
	$dat->finish;

	# now determine what id that entry has
	my $entry_id;
	my $gid_query="SELECT id FROM fluxdata ORDER BY id DESC LIMIT 1";
	print "executing query: $gid_query\n";
	my $gid=$dbh->prepare($gid_query);
	$gid->execute;
	while (my ($idresponse)=$gid->fetchrow){
	    $entry_id=$idresponse;
	}
	$gid->finish;
	
	# now make a dummy observation entry
	my $obs_query="INSERT INTO observation (";
	my $obs_names;
	my $obs_values;
	$obs_names="n_if";
	$obs_values="1";
	if ($parameters{'source'}){
	    $obs_names.=",source";
	    $obs_values.=",'".$parameters{'source'}."'";
	}
	if ($parameters{'ra'}){
	    $obs_names.=",ra";
	    $obs_values.=",".&sexagesimal_to_decimal($parameters{'ra'});
	}
	if ($parameters{'dec'}){
	    $obs_names.=",dec";
	    $obs_values.=",".&sexagesimal_to_decimal($parameters{'dec'});
	}
	if ($parameters{'time'}){
	    $obs_names.=",time";
	    $obs_values.=",'".$parameters{'time'}."'";
	}
	if ($parameters{'arrayname'}){
	    $obs_names.=",arrayname";
	    $obs_values.=",'".$parameters{'arrayname'}."'";
	}
	if ($parameters{'name'}){
	    $obs_names.=",rpfits_file,project_code";
	    my $projcode=$parameters{'name'};
	    $projcode=~s/^.*\.([^\.]*)/$1/;
	    $obs_values.=",'".$parameters{'name'}."','".$projcode."'";
	}
	if ($parameters{'calcode'}){
	    $obs_names.=",calcode";
	    $obs_values.=",'".$parameters{'calcode'}."'";
	}
	$obs_names.=",processed_ids";
	$obs_values.=",'{".$entry_id."}'";
	if ($parameters{'antaz'}){
	    $obs_names.=",az";
	    $obs_values.=",".$parameters{'antaz'};
	}
	if ($parameters{'antel'}){
	    $obs_names.=",el";
	    $obs_values.=",".$parameters{'antel'};
	}
	if ($parameters{'airtemp'}){
	    $obs_names.=",airtemp";
	    $obs_values.=",".$parameters{'airtemp'};
	}
	if ($parameters{'arrayname'}){
	    $obs_names.=",arrayname";
	    $obs_values.=",'".$parameters{'arrayname'}."'";
	}
	if ($parameters{'central_frequency'}){
	    $obs_names.=",if_freq,if_nchans,if_bw";
	    $obs_values.=",'{".$parameters{'central_frequency'}."}',".
		"'{".$parameters{'nchannels'}."}',".
		"'{".$parameters{'bandwidth'}."}'";
	}
	if ($parameters{'chi'}){
	    $obs_names.=",chi";
	    $obs_values.=",".$parameters{'chi'};
	}
	if ($parameters{'jyperk'}){
	    $obs_names.=",jyperk";
	    $obs_values.=",".$parameters{'jyperk'};
	}
	if ($parameters{'pntra'}){
	    $obs_names.=",pntra";
	    $obs_values.=",".$parameters{'pntra'};
	}
	if ($parameters{'pntdec'}){
	    $obs_names.=",pntdec";
	    $obs_values.=",".$parameters{'pntdec'};
	}
	if ($parameters{'evector'}){
	    $obs_names.=",evector";
	    $obs_values.=",".$parameters{'evector'};
	}
	if ($parameters{'relhumid'}){
	    $obs_names.=",relhumid";
	    $obs_values.=",".$parameters{'relhumid'};
	}
	if ($parameters{'smonrms'}){
	    $obs_names.=",smonrms";
	    $obs_values.=",".$parameters{'smonrms'};
	}
	if ($parameters{'wind'}){
	    $obs_names.=",wind";
	    $obs_values.=",".$parameters{'wind'};
	}
	if ($parameters{'winddir'}){
	    $obs_names.=",winddir";
	    $obs_values.=",".$parameters{'winddir'};
	}
	if ($parameters{'systemp'}){
	    my @tsysarray=@{$parameters{'systemp'}};
	    $obs_names.=",xtsys,ytsys";
	    $obs_values.=",'{";
	    for (my $ii=0;$ii<=$#tsysarray;$ii++){
		if ($ii>0){
		    $obs_values.=",";
		}
		$obs_values.=$tsysarray[$ii];
	    }
	    $obs_values.="}','{";
	    for (my $ii=0;$ii<=$#tsysarray;$ii++){
		if ($ii>0){
		    $obs_values.=",";
		}
		$obs_values.=$tsysarray[$ii];
	    }
	    $obs_values.="}'";
	}
	$obs_query.=$obs_names.") VALUES (".$obs_values.")";
	print "query: $obs_query\n";
	my $obs=$dbh->prepare($obs_query);
	my $rc=$obs->execute;
	if ($rc!=1){
	    # we may have gotten an error!
	    if ($dat->err!=0){
		print "error inserting into observation database!\n";
		$obs->finish;
		return -1;
	    }
	}
	$obs->finish;

	# now determine what id that entry has
	my $obs_entry_id;
	my $gid_query="SELECT id FROM observation ORDER BY id DESC LIMIT 1";
	print "executing query: $gid_query\n";
	my $gid=$dbh->prepare($gid_query);
	$gid->execute;
	while (my ($idresponse)=$gid->fetchrow){
	    $obs_entry_id=$idresponse;
	}
	$gid->finish;

	# compress the dataset for entry into the database
	my $compressed_dataset=
	    &compress_and_copy_dataset($parameters{'dataset'},
				       $parameters{'working_directory'});
	
	# update the fluxdata entry
	$dat_query="UPDATE fluxdata SET (observation_ids,uv_data) = (".
	    "'{".$obs_entry_id."}',lo_import('".$compressed_dataset."')) ".
	    "WHERE id=".$entry_id;
	print "query: $dat_query\n";
	$dat=$dbh->prepare($dat_query);
	$dat->execute;
	$dat->finish;

	# remove the remote dataset
	&remove_remote_data($compressed_dataset);
    }

}

sub remove_remote_data {
    my ($remotedata)=@_;

    my $database_server_login="postgres\@mentok";
    my $database_server_port=2222;
    my $database_server_path="/var/lib/postgresql";
    my $remove_command="ssh -p ".$database_server_port;
    $remove_command.=" -i ~/.ssh/id_rsa";
    $remove_command.=" ".$database_server_login." ";
    $remove_command.="rm -f ".$remotedata;
    print "executing: $remove_command\n";
    system $remove_command;

}

sub compress_and_copy_dataset {
    my ($source,$working_directory)=@_;
    
    # preparation
    $working_directory=~s/\/$//;

    my $input_dataset=$source;
    my $output_name=$input_dataset.".tar.bz2";
    my $output_dataset=$working_directory."/".$output_name;
    my $compress_command="tar -cjf";
    $compress_command.=" ".$output_dataset;
    $compress_command.=" ".$input_dataset;
    print "executing: $compress_command\n";
    system $compress_command;

    # copy it to the database machine
    my $database_server_login="postgres\@mentok";
    my $database_server_port=2222;
    my $database_server_path="/var/lib/postgresql";
    my $copy_command="scp -P ".$database_server_port;
    $copy_command.=" -i ~/.ssh/id_rsa";
    $copy_command.=" ".$output_dataset;
    $copy_command.=" ".$database_server_login.":.";
    print "executing: $copy_command\n";
    system $copy_command;

    # remove it from the local system
    my $remove_command="rm -f ".$output_dataset;
    print "executing: $remove_command\n";
    system $remove_command;

    return $database_server_path."/".$output_name;
}

sub month_to_number {
    my ($month_name)=@_;
    
    my @month_names=("JAN","FEB","MAR","APR","MAY","JUN","JUL",
		     "AUG","SEP","OCT","NOV","DEC");
    my @month_numbers=("01","02","03","04","05","06","07",
		       "08","09","10","11","12");
    my $month_number=-1;
    for (my $i=0;$i<=$#month_names;$i++){
	if ($month_name eq $month_names[$i]){
	    $month_number=$month_numbers[$i];
	    last;
	}
    }

    return $month_number;
}

sub sexagesimal_to_decimal {
    my ($sexagesimal)=@_;

    print "sexagesimal: $sexagesimal\n";
    my @sexels=split(/[\:\s]+/,$sexagesimal);
    my $negative=1;
    if ($sexagesimal=~/^\-/){
	$negative=-1;
    }
    my $decimal=$negative*$sexels[0];
    print $sexels[0]." ".$decimal."\n";
    $decimal+=$sexels[1]/60.0;
    print $sexels[1]." ".$decimal."\n";
    $decimal+=$sexels[2]/3600.0;
    print $sexels[2]." ".$decimal."\n";
    $decimal*=$negative;
    print $decimal."\n";

    return $decimal;
}

sub make_measurements {
    my ($source,%parameters)=@_;

    my $miriad_closure_command="closure";

    # get closure phases
    my $closure_phase_actual;
    my $closure_phase_theoretical;
    my $input_dataset=$source;
    my $closure_command=$miriad_closure_command;
    $closure_command.=" vis=".$input_dataset;
    $closure_command.=" stokes=i";
    print "executing $closure_command\n";
    open(CLOSURE,"-|")||exec $closure_command." 2>&1";
    while(<CLOSURE>){
	chomp;
	my $line=$_;
	my @els=split(/\s+/,$line);
	if ($line=~/^Actual\sclosure\sphase/){
	    $closure_phase_actual=$els[$#els];
	} elsif ($line=~/^Theoretical\sclosure\sphase/){
	    $closure_phase_theoretical=$els[$#els];
	} elsif ($line=~/^\#\#\#\sFatal\sError/){
	    # this command has failed
	    $closure_phase_actual=-999.999;
	    $closure_phase_theoretical=-999.999;
	}
    }
    close(CLOSURE);
    $parameters{'closure_phase_actual'}=$closure_phase_actual;
    $parameters{'closure_phase_theoretical'}=$closure_phase_theoretical;

    # get triple amplitudes
    my $tripleamp_value;
    my $tripleamp_scatter_actual;
    my $tripleamp_scatter_theoretical;
    $closure_command=$miriad_closure_command;
    $closure_command.=" vis=".$input_dataset;
    $closure_command.=" stokes=i";
    $closure_command.=" options=amplitude";
    print "executing $closure_command\n";
    open(CLOSURE,"-|")||exec $closure_command." 2>&1";
    while(<CLOSURE>){
	chomp;
	my $line=$_;
	$line=~s/\:/\: /g;
	my @els=split(/\s+/,$line);
	if ($line=~/^Mean\samplitude/){
	    $tripleamp_value=$els[$#els];
	} elsif ($line=~/^Actual\samplitude\srms/){
	    $tripleamp_scatter_actual=$els[$#els];
	} elsif ($line=~/^Theoretical\samplitude\srms/){
	    $tripleamp_scatter_theoretical=$els[$#els];
	} elsif ($line=~/^\#\#\#\sFatal\sError/){
	    # this command has failed
	    $tripleamp_value=-999.999;
	    $tripleamp_scatter_actual=-999.999;
	    $tripleamp_scatter_theoretical=-999.999;
	}
    }
    close(CLOSURE);
    $parameters{'tripleamp_value'}=$tripleamp_value;
    $parameters{'tripleamp_scatter_actual'}=$tripleamp_scatter_actual;
    $parameters{'tripleamp_scatter_theoretical'}=$tripleamp_scatter_theoretical;

    return %parameters;

}

#sub which_source {
#    my $thisdir=getcwd;
#    
#    $thisdir=~s/^.*\/([^\/]*)$/$1/;
#
#    return $thisdir;
#}

sub gather_data {
    my ($source,%parameters,%options)=@_;

    my $miriad_uvlist_command="uvlist";

    $parameters{'dataset'}=$source;

    # get the frequency configuration
    my $uvlist_command=$miriad_uvlist_command;
    $uvlist_command.=" vis=".$source;
    $uvlist_command.=" options=spectral";
    print "executing: $uvlist_command\n";

    open(UVLIST,"-|")||exec $uvlist_command;
    my ($startchan,$numchan,$startfreq,$freqinterval);
    while(<UVLIST>){
	chomp;
	my $line=$_;
	my @els=split(/\s+/,$line);
	if ($line=~/^Start\schannel/){
	    $startchan=$els[$#els];
	} elsif ($line=~/^Number\sof\schannels/){
	    $numchan=$els[$#els];
	} elsif ($line=~/Start\sfrequency/){
	    $startfreq=$els[$#els];
	} elsif ($line=~/Frequency\sincrement/){
	    $freqinterval=$els[$#els];
	}
    }
    close(UVLIST);

    if ($startfreq<1000.0){
	$startfreq*=1000.0;
	$freqinterval*=1000.0;
    }
    $parameters{'start_freq'}=$startfreq;
    $parameters{'freq_interval'}=$freqinterval;
    $parameters{'start_channel'}=$startchan;
    $parameters{'nchannels'}=$numchan;
#    if ($numchan>1000){
#	# we have CABB data!
#	$parameters{'cabb_data'}=1;
#	return %parameters;
#    }

    # work out the central frequency and bandwidth
    my $endfreq=$startfreq+($numchan-$startchan)*$freqinterval;
    my $bandwidth=$endfreq-$startfreq;
    my $centralfreq=($endfreq-$startfreq)/2+$startfreq;
    $parameters{'bandwidth'}=$bandwidth;
    # round the central frequency to the nearest MHz
    $parameters{'central_frequency'}=round($centralfreq,3);

    # now some observing parameters
    my $logfile="/tmp/uvlist.log";
    $uvlist_command=$miriad_uvlist_command;
    $uvlist_command.=" vis=".$source;
    $uvlist_command.=" options=var,full";
    $uvlist_command.=" log=".$logfile;
    print "executing: $uvlist_command\n";
    system $uvlist_command;
    # check that the logfile has been created
    if (!-e $logfile){
	print "unable to get output of uvlist!\n";
	exit;
    }
    open(LOGFILE,$logfile);
    my $started=0;
    my $left_to_get=0;
    my $getting_parameter;
    my @paramsget;
    while(<LOGFILE>){
	chomp;
	my $line=$_;
	# any "(no value set)" will cause us problems, so we fix that
	$line=~s/\(no\svalue\sset\)/\(novalueset\)/g;
	if ($line=~/^Header\svariables/){
	    $started=1;
	} elsif ($started==1){
	    $line=~s/\:/ /g;
#	    $line=~s/(\d)(\-)/$1 $2/g;
	    my @els=split(/\s+/,$line);
	    for (my $j=0;$j<=$#els;$j++){
		if (($els[$j] eq "airtemp")||($els[$j] eq "antaz")||
		    ($els[$j] eq "antel")||($els[$j] eq "chi")||
		    ($els[$j] eq "evector")||($els[$j] eq "jyperk")||
		    ($els[$j] eq "pntdec")||($els[$j] eq "pntra")||
		    ($els[$j] eq "relhumid")||($els[$j] eq "smonrms")||
		    ($els[$j] eq "wind")||($els[$j] eq "winddir")||
		    ($els[$j] eq "nants")||($els[$j] eq "source")||
		    ($els[$j] eq "ra")||($els[$j] eq "dec")||
		    ($els[$j] eq "name")||($els[$j] eq "calcode")){
		    my $this_parameter=$els[$j];
		    $j++;
		    my $this_value=$els[$j];
		    if (($this_parameter eq "ra")||($this_parameter eq "dec")){
			$j++;
			$this_value.=" ".$els[$j];
			$j++;
			$this_value.=" ".$els[$j];
		    }
		    if ($this_value eq "(novalueset)"){
			$this_value=-999.999; # magic number alert!
		    }
#		    if (($this_parameter eq "source")&&
#			($this_value!~/[\+\-]/)){
#			# the source doesn't look right
##			$this_value=$source;
##			$this_value=~s/^(.*)\..*$/$1/;
#			$this_value=&which_source();
#		    }
		    $parameters{$this_parameter}=$this_value;
#		    if ($output_debug>1){
#			print "got $this_parameter : $parameters{$this_parameter}\n";
#		    }
		} elsif ($left_to_get>0){
		    if ($els[$j] eq $getting_parameter){
			next;
		    }
		    if ($els[$j] eq "(novalueset)"){
			$left_to_get=0;
			next;
		    }
		    push @paramsget,$els[$j];
		    $left_to_get--;
		    if ($left_to_get==0){
#			$getting_parameter.="_if".$ifs[$i];
			$parameters{$getting_parameter}=[@paramsget];
		    }
		} elsif (($els[$j] eq "xtsys")||
			 ($els[$j] eq "xyphase")||($els[$j] eq "ytsys")||
			 ($els[$j] eq "xcaljy")||($els[$j] eq "ycaljy")||
			 ($els[$j] eq "xgtp")||($els[$j] eq "ygtp")||
			 ($els[$j] eq "xsdo")||($els[$j] eq "ysdo")||
			 ($els[$j] eq "systemp")){
		    if ($left_to_get==0){
			$getting_parameter=$els[$j];
			$left_to_get=$parameters{"nants"};
#			if ($output_debug>1){
#			    print "starting parameter get for $getting_parameter, $left_to_get values to get\n";
#			}
			undef @paramsget;
		    }
		}
	    }
	}
    }
    close(LOGFILE);

    # get the start time
    $uvlist_command=$miriad_uvlist_command;
    $uvlist_command.=" vis=".$source;
    $uvlist_command.=" options=full";
    $uvlist_command.=" log=".$logfile;
    print "executing: $uvlist_command\n";
    system $uvlist_command;
#    open(UVLIST,"-|")||exec $uvlist_command;
    open(UVLIST,$logfile);
    while(<UVLIST>){
	chomp;
	my $line=$_;
	if ($line=~/.*(\d+\D{3}\d{2}\:\d{2}\:\d{2}\:\d{2})\s.*/){
	    my $fits_time=$1;
	    $fits_time=~/(\d+)(\D{3})(\d{2})\:(.*)/;
	    my $time_year=$1;
	    my $time_month_name=$2;
	    my $time_day=$3;
	    my $time_time=$4;
	    if ($time_year<1900){
		if (($time_year>=0)&&($time_year<=10)){
		    $time_year+=2000;
		} else {
		    $time_year+=1900;
		}
	    }
	    my $time_month_number=&month_to_number($time_month_name);
	    $parameters{'time'}=$time_year."-".$time_month_number."-".
		$time_day." ".$time_time;
	}
    }
    close(UVLIST);

    # get the array name
    if ($options{'force_array'}){
	$parameters{'arrayname'}=$options{'force_array'};
    }
    
    # replace forced parameters
    if ($options{'force_source'}){
	$parameters{'source'}=$options{'force_source'};
    }

    return %parameters;
}

sub round {
    my $number = shift || 0;
    my $dec = 10 ** (shift || 0);
    return int( $dec * $number + .5 * ($number <=> 0)) / $dec;
}
